package com.yanftch.stopcoding.ui

import java.awt.Graphics
import java.awt.Image
import java.awt.image.BufferedImage
import javax.swing.JPanel
class ImagePanel(private val image: BufferedImage) : JPanel() {
    override fun paintComponent(g: Graphics) {
        super.paintComponent(g)

        // 获取当前面板的大小
        val panelWidth = width
        val panelHeight = height

        // 计算缩放后的宽高，保持纵横比
        val aspectRatio = image.width.toDouble() / image.height.toDouble()
        val scaledWidth: Int
        val scaledHeight: Int

        if (panelWidth / panelHeight > aspectRatio) {
            // 按照高度缩放
            scaledHeight = panelHeight
            scaledWidth = (panelHeight * aspectRatio).toInt()
        } else {
            // 按照宽度缩放
            scaledWidth = panelWidth
            scaledHeight = (panelWidth / aspectRatio).toInt()
        }

        // 计算图像居中的位置
        val x = (panelWidth - scaledWidth) / 2
        val y = (panelHeight - scaledHeight) / 2

        // 绘制裁剪后的图像
        g.drawImage(image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH), x, y, null)
    }
}


//class ImagePanel(private val image: BufferedImage) : JPanel() {
//    override fun paintComponent(g: Graphics) {
//        super.paintComponent(g)
//
//        // 获取当前面板的大小
//        val width = width
//        val height = height
//
//        // 计算缩放后的宽高，保持纵横比
//        val scaledImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH)
//        val imgWidth = scaledImage.getWidth(null)
//        val imgHeight = scaledImage.getHeight(null)
//
//        // 计算图像居中的位置
//        val x = (width - imgWidth) / 2
//        val y = (height - imgHeight) / 2
//
//        // 绘制图像
//        g.drawImage(scaledImage, x, y, null)
//    }
//}
